﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class BallController : MonoBehaviour
{

    private Rigidbody2D ball;
    public float speed = 5f;
    public Text score1, score2;
    // Use this for initialization
    void Start()
    {
        ball = GetComponent<Rigidbody2D>();
        InitBall();
    }

    // Update is called once per frame
    void Update()
    {
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.collider.tag == "Player1"|| collision.collider.tag == "Player2")
        {
            Vector2 speed = ball.velocity;
            speed.y  = collision.rigidbody.velocity.y/2f+speed.y/2f;
            ball.velocity = speed;
            if(collision.collider.tag == "Player1")
            {
                score1.text = (int.Parse(score1.text) + 1).ToString();
            }
            else
            {
                score2.text = (int.Parse(score2.text) + 1).ToString();
            }
        }
    }

    void InitBall()
    {
        ball.transform.position = Vector3.zero;
        ball.velocity = new Vector2(Random.Range(0, 2) == 0 ? speed : -speed, 0);
    }

    public void ResetBall()
    {
        InitBall();
        score1.text = "0";
        score2.text = "0";
    }
}
